﻿$(document).ready(function () {
    $('.frmLogout').hide();
});

function doLogin() {

    var un = $('.tbUN').val().trim();
    var pw = $('.tbPW').val().trim();

    if (un == "" || pw == "") {
        alert("username and password are not empty.");
        return;
    }

    $.ajax({
        type: 'POST',
        url: 'http://localhost:8788/doLogin.aspx/Login',
        data: "{'username':'" + un + "' , 'password':'" + pw + "'}",
        contentType: "application/json",
        dataType: "json",
        success: function (result) {
            if (result.d == true) {
                alert("Login success.");
                $('.frmLogin').hide();
                $.cookie("user", un, { expires: 1 });
                $('.lbUserName').text('Welcome: ' + un);
                $('.frmLogout').show();
                window.location.href = "http://localhost:8788/upload.aspx";
            } else {
                alert("Login fail.");
            }
        },
        failure: function (result) {
            alert(result.d);
        }
    });
}
function doLogout() {

    $.ajax({
        type: 'POST',
        url: 'http://localhost:8788/doLogin.aspx/logOut',
        data: "{}",
        contentType: "application/json",
        dataType: "json",
        success: function (result) {
            alert(result.d);
            $.cookie("user", null);
            $('.frmLogout').hide();
            $('.frmLogin').show();
            window.location.href = "http://localhost:8788/Home.aspx";
        },
        failure: function (result) {
            alert(result.d);
        }
    });


}

//getcookie
function getCookie(c_name) {
    var i, x, y, ARRcookies = document.cookie.split(";");
    for (i = 0; i < ARRcookies.length; i++) {
        x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
        y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
        x = x.replace(/^\s+|\s+$/g, "");
        if (x == c_name) {
            return unescape(y);
        }
    }
}

//set cookie
function setCookie(c_name, value, exdays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
    document.cookie = c_name + "=" + c_value;
}

//check cookie available
function checkCookie() {
    var username = getCookie("user");
    if (username != null && username != "") {
        //        alert("Welcome again " + username);
        $('.lbUserName').text('Welcome: ' + username);
        $('.frmLogin').hide();
        $('.frmLogout').show();

    }
    else {

    }
}